package com.itheima.tliasmanager.filter;

import com.itheima.tliasmanager.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURL().toString();
        log.info("Filter 拦截的请求路径是：{}",url);
        if (url.contains("login")){
            log.info("Filter 登录操作，放行");
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("token");
        if (token == null){
            log.info("Filter 拦截到请求没有令牌, 直接封装未授权响应结果");
            response.setStatus(401);
            return;
        }

        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("Filter 令牌无效, 直接封装未授权响应结果");
            response.setStatus(401);
            return;
        }

        log.info("Filter 过滤请求,令牌有效，放行");
        filterChain.doFilter(request,response);

    }
}
